//
//  SSCommonSpecController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/3/20.
//

import UIKit


import UIKit
import SwiftyJSON


class SSCommonSpecController: UIViewController {
    var specResult: SpecResult?     // 闭包
    var items: Array<SSListSpecs> = []
    //选过的标签
    var selectedItems: Array<SSSpec> = []
    var baseFeeInt:Float = 0
    
    @IBOutlet weak var tableView: UITableView!
    var headerModel : ListCombo = ListCombo()
//    var selectedIndexPath: IndexPath?
    
    @IBOutlet weak var surebBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "SSSpecTableViewCell", bundle: Bundle.init(for: SSSpecTableViewCell.self)), forCellReuseIdentifier: "SSSpecTableViewCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        
        surebBtn.layer.masksToBounds = true
        surebBtn.layer.cornerRadius = 8
        
        getListNetwork()
    }
    
    func numberResult(_ finished: @escaping SpecResult) {
        specResult = finished
    }
    
    //MARK: -networing
    //list
    func getListNetwork() {
        let param = [
            "parentId": "\(self.headerModel.id)"
        ] as [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getItemSpecs_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let data = json["data"]["listSpecs"].arrayValue
                var items: Array<SSListSpecs> = []
                
                for(i, num) in data.enumerated() {//区
                    let obj = SSListSpecs()
                    obj.isOptional = num["isOptional"].stringValue
                    obj.name = num["name"].stringValue
                    var subDatas: Array<SSSpec> = []
                    let subobj = num["listSubSpecs"].arrayValue
                    for(index, num1) in subobj.enumerated() {//行
                        let newn = SSSpec()
                        newn.name = num1["name"].stringValue
                        newn.fee = num1["fee"].stringValue
                        newn.id = num1["id"].stringValue
                        subDatas.append(newn)
                        self.selectedItems.forEach { (num2) in//设置为选中状态
                            if(num2.id == newn.id){
                                newn.isSelected = true
                                obj.selectedIndexPath = IndexPath(row: index, section: i)
                            }
                        }
                    }
                    obj.listItem = subDatas
                    items.append(obj)
                }
                self.items = items
                self.tableView.reloadData()
                print("")
            }
        }
    }
    

    @IBAction func sureAction(_ sender: Any) {
        var selectItem:Array<SSSpec> = []
        for listSpecs in self.items {

            if (listSpecs.selectedIndexPath != nil) {
                for specs in listSpecs.listItem {
                    if specs.isSelected {
                        selectItem.append(specs)
                    }
                }
            }else{
                if listSpecs.isOptional == "0" {
                    UIViewController.current().view.makeToast("请选择必选项")
                    return
                }
            }
        }
        dismiss(animated: true) {
            self.specResult!(selectItem)
        }
        
    }
}

extension SSCommonSpecController: UITableViewDelegate, UITableViewDataSource
{
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.items.count
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return (54 + 6)
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        var title = ""
        if self.items.count > 0 {
            title = (self.items[section] ).name
        }
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 54 + 6))
        view.backgroundColor = UIColor.white
        
        var sectionH = 10
        
        let sectionView = UIView()
        view.addSubview(sectionView)
        sectionView.backgroundColor = UIColor.init(hex: "#F2F2F2")
        sectionView.snp.makeConstraints { make in
            make.height.equalTo(sectionH)
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
        }
        if section == 0 {
//            sectionH = 10
            sectionView.backgroundColor = UIColor.white
        }

        let titleLab = UILabel()
        titleLab.text = title
        titleLab.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        titleLab.textColor = UIColor.black
        view.addSubview(titleLab)
        titleLab.snp.makeConstraints { make in
            make.width.equalTo(300)
            make.height.equalTo(22)
            make.top.equalTo(sectionView.snp.bottom).offset(16)
            make.left.equalTo(16)
        }
        
        let descLab = UILabel()
        descLab.text = "单选"
        descLab.font = UIFont.systemFont(ofSize: 10)
        descLab.textColor = UIColor.app6Color
        view.addSubview(descLab)
        descLab.snp.makeConstraints { make in
            make.width.equalTo(150)
            make.height.equalTo(14)
            make.left.equalTo(16)
            make.top.equalTo(titleLab.snp.bottom)
        }
        
        let imageV = UIImageView()
        view.addSubview(imageV)
        if self.items[section].isOptional == "0" {
            imageV.image = UIImage(named: "require")
        }else{
            imageV.image = UIImage(named: "option")
        }

        imageV.snp.makeConstraints { make in
            make.width.equalTo(38)
            make.height.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(sectionView.snp.bottom).offset(16)
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items[section].listItem.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SSSpecTableViewCell") as! SSSpecTableViewCell
        cell.indexPath = indexPath
        cell.isfeeHiden = true
        cell.setData(data: self.items[indexPath.section].listItem[indexPath.row] )
        if self.items[indexPath.section].selectedIndexPath?.row == indexPath.row{
            cell.setChecked(isselected: true)
            self.items[indexPath.section].listItem[indexPath.row].isSelected = true
        }else{
            cell.setChecked(isselected: false)
            self.items[indexPath.section].listItem[indexPath.row].isSelected = false
        }
        cell.getIndexWithClosure { (indexPath) -> Void in
            
            //
            let superItem:SSListSpecs = self.items[indexPath.section]
            if(superItem.selectedIndexPath != nil){
                for spec in superItem.listItem {
                    if spec.isSelected {
                        spec.isSelected = false
                    }
                }
            }
            
            self.items[indexPath.section].selectedIndexPath = indexPath
            //当前item作为当前区选中的item
            let selectedItem:SSSpec = self.items[indexPath.section].listItem[indexPath.row]
            self.items[indexPath.section].selectedItem = selectedItem
            self.tableView.reloadSections(NSIndexSet(index: indexPath.section) as IndexSet, with: UITableView.RowAnimation.none)
            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }
}
